﻿using System;
using System.Diagnostics.Contracts;
using System.Net;
using System.Runtime.CompilerServices;
using System.Text;
using CoreLibrary;
using CoreLibrary.Service;
using Newtonsoft.Json;

namespace Modules.API {

    public class CurrencyExchangeService : ServiceBase, ICurrencyExchangeService {

        const string Url = "http://api.fixer.io/latest?base={0}&symbols={1}";

        protected override void OnInit()    {}
        protected override void OnDestroy() {}
        protected override void OnStart()   {}
        protected override void OnStop()    {}

        public SearchCurrencyResult Search(SearchCurrencyRequest request) {
            try {
                var currRequest = CreateInternalRequest(request.From, request.To);
                using (var response = (HttpWebResponse) currRequest.GetResponse()) {
                    var result = Encoding.UTF8.GetString(IOUtil.Read(response.GetResponseStream()));
                    var currencyResult = JsonConvert.DeserializeObject<CurrencyResult>(result);
                    return new SearchCurrencyResult {
                        From = currencyResult.Base,
                        To = request.To,
                        Date = currencyResult.Date,
                        Rate = currencyResult.Rates.CNY
                    };
                }
            }
            catch (WebException exception) {
                 throw new Exception(exception.Message);
            }
            catch (Exception exception) {
                 throw;
            }
        }

        protected static HttpWebRequest CreateInternalRequest(string from, string to) {
            var request = (HttpWebRequest)WebRequest.Create(string.Format(Url, from, to));
            request.Method           = "GET";
            request.ProtocolVersion  = HttpVersion.Version11;
            request.Timeout          = 500000000;
            request.ReadWriteTimeout = 500000000;
            return request;
        }

        public class CurrencyResult {

            [JsonProperty(PropertyName = "base")]
            public string Base   { get; set; }

            [JsonProperty(PropertyName = "date")]
            public DateTime Date { get; set; }

            [JsonProperty(PropertyName = "rates")]
            public Rates Rates   { get; set; }

        }

        public class Rates {

            [JsonProperty(PropertyName="CNY")]
            public double CNY { get; set; }
        }
    }
}